package org.roger.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.store.FSDirectory;

public class IndexReaderUtil {
	
	private static Map<String,IndexReader> indexReaderMap = new HashMap<String,IndexReader>();
	
	/**
	 * 得到当前索引的IndexReader
	 * @param indexPath
	 * @return
	 */
	public static synchronized IndexReader getIndexReader(String indexPath){
		
		if(indexReaderMap.containsKey(indexPath)){
			return indexReaderMap.get(indexPath);
		}else{
			IndexReader reader = null;
			try {
				reader = DirectoryReader.open(FSDirectory.open(new File(indexPath)));
				indexReaderMap.put(indexPath, reader);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return reader;
		}
	}
	
	/**
	 * 关闭所有的indexReader
	 */
	public static void closeAll(){
		if(indexReaderMap != null && indexReaderMap.size() > 0){
			Set<String> keySet = indexReaderMap.keySet();
			Iterator<String> keys = keySet.iterator();
			while(keys.hasNext()){
				try {
					indexReaderMap.get(keys.next()).close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			indexReaderMap.clear();
		}
	}
	
	/**
	 * 关闭当前索引的indexReader
	 * @param indexPath 当前索引路径
	 */
	public static void close(String indexPath){
		if(indexReaderMap != null && indexReaderMap.containsKey(indexPath)){
			try {
				indexReaderMap.get(indexPath).close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			indexReaderMap.remove(indexPath);
		}
	}
}
